package com.comleader.operator.service;

import static com.comleader.operator.pojo.entity.table.DictDataTableDef.DICT_DATA;

import java.io.Serializable;
import java.util.List;

import org.springframework.stereotype.Service;

import com.comleader.operator.common.util.DictCacheUtil;
import com.comleader.operator.mapper.DictDataMapper;
import com.comleader.operator.pojo.entity.DictDataEntity;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;

/**
 * 字典数据表 服务层实现。
 *
 * @author 连新景
 * @since 1.0
 */
@Service
public class DictDataService extends ServiceImpl<DictDataMapper, DictDataEntity> {

    public List<DictDataEntity> listDictDataByCode(String dictCode) {
        // 从缓存中查询不到数据返回null,为null时表示一定没查询过数据库，不为null时即使为空list也表示已经查询过数据库了
        List<DictDataEntity> dictDataList = DictCacheUtil.getDictCache(dictCode);
        if (dictDataList != null) {
            return dictDataList;
        }
        // 库中查询不到返回的是空list,也放到缓存中，避免缓存穿透
        dictDataList = list(QueryWrapper.create().from(DICT_DATA).where(DICT_DATA.CODE.eq(dictCode)).orderBy(DICT_DATA.SORT.asc()));
        DictCacheUtil.setDictCache(dictCode, dictDataList);
        return dictDataList;
    }

    public void saveDictData(DictDataEntity dictData) {
        if (save(dictData)) {
            setDictCache(dictData.getCode());
        }
    }

    public void updateDictData(DictDataEntity dictData) {
        if (updateById(dictData)) {
            setDictCache(dictData.getCode());
        }
    }

    private void setDictCache(String code) {
        List<DictDataEntity> dictDataList = list(QueryWrapper.create().where(DICT_DATA.CODE.eq(code)).orderBy(DICT_DATA.SORT.asc()));
        DictCacheUtil.setDictCache(code, dictDataList);
    }

    public void delete(Serializable id) {
        DictDataEntity dictData = getById(id);
        if (removeById(id)) {
            setDictCache(dictData.getCode());
        }
    }

    public boolean deleteByCode(String dictCode) {
        return remove(QueryWrapper.create().where(DICT_DATA.CODE.eq(dictCode)));
    }

}